﻿/* File Created: 三月 19, 2014 */
(function ($) {
    $.dcorder = {};
    $.extend($.dcorder,
    {
        div_mask: "#J_mask",
        oName: "#J_name",
        oPhone: "#J_phone", //手机号
        oSMSCode: "#J_yzm_txt",
        oSendSMSBtn: "#btn_getcode",
        btnSubmit: "#btn-submit", //提交按钮
        oDealer: "#J_dealer",
        oCity: "#J_city",
        oProvince: "#J_province",
        callback: null,
        init: function (options) {
            $.extend($.dcorder, options);
            //从cookie中读取用户记录
            $.dcorder.utils.recoverInput();
            $("#div_fail").find("a").click(function () {
                $("#div_fail .pop-close").click();
                $("#J_form").show();
            });
            $.dcorder.loadprovince();
            $(document).on("change", "#J_province", function () {
                $.dcorder.loadcity($(this).val());
            });
            $(document).on("change", "#J_city", function () {
                $.dcorder.loaddealer($(this).val());
            });
            $.ajax({
                type: "GET",
                url: llb_global.config.api + "api/Base/IpLocate",
                timeout: 2000,
                dataType: 'jsonp',
                jsonp: "callback",
                jsonpCallback: "$.dcorder.initLocation"
            });
            //绑定登录按钮
            $($.dcorder.btnSubmit).click($.dcorder.submitOrderFlow.submitOrder);
            $($.dcorder.oSendSMSBtn).click($.dcorder.sms.sendsms);
        },
        utils: {
            saveInput: function () {
                //保存订单中提交的数据
                var saveValue = {
                    "phone": $($.dcorder.oPhone).val(),
                    "name": encodeURI($($.dcorder.oName).val()),
                    "dealer": $($.dcorder.oDealer).val()
                };
                llb_global.utils.setCookie("dcorder", JSON.stringify(saveValue));
            },
            recoverInput: function () {
                if (llb_global.utils.readcookie("dcorder") !== "") {
                    try {
                        var cb = JSON.parse(llb_global.utils.readcookie("dcorder"));
                        if (typeof (cb) !== "undefined") {
                            if (typeof (cb.phone) !== "undefined") {
                                $($.dcorder.oPhone).val(decodeURI(cb.phone));
                            }
                            if (typeof (cb.name) !== "undefined") {
                                $($.dcorder.oName).val(decodeURI(cb.name));
                            }
                        }
                    } catch (e) { }
                }
            }
        },
        //验证方法集合
        validateFn: {
            checkName: function () {
                return $.validator.validate({
                    el: $($.dcorder.oName),
                    failCallback: function (err) {
                        if (err) {
                            tips.setError(err);
                        }
                    },
                    customCheck: function () {
                        var vr = $.validator.createResult();
                        var name = $.trim($($.dcorder.oName).val());
                        if (name.length === 0) {
                            vr.errMsg = "请输入姓名";
                            vr.success = false;
                        } else if (name.length < 2 || name.length > 6) {
                            vr.errMsg = "请输入姓名";
                            vr.success = false;
                        } else if (!RegExp(/^[\u4e00-\u9fa5\\]+$/).test(name)) {
                            vr.errMsg = "请输入姓名";
                            vr.success = false;
                        } else {
                            vr.success = true;
                        }
                        return vr;
                    }
                }).IsPass();
            },
            checkPhone: function () {
                return $.validator.validate("phone", {
                    el: $($.dcorder.oPhone),
                    allowEmpty: false,
                    failCallback: function (err) {
                        if (err) {
                            tips.setError(err);
                        }
                    }
                }).IsPass();
            },
            checkCode: function () {
                return $.validator.validate({
                    el: $($.dcorder.oSMSCode),
                    failCallback: function (err) {
                        if (err) {
                            tips.setError(err);
                        }
                    },
                    customCheck: function () {
                        var vr = $.validator.createResult();
                        var code = $($.dcorder.oSMSCode).val();
                        if (!code.trim()) {
                            vr.errMsg = "请输入验证码";
                            vr.success = false;
                        } else {
                            vr.success = true;
                        }
                        return vr;
                    }
                }).IsPass();
            },
            checkDealer: function () {
                return $.validator.validate({
                    el: $($.dcorder.oDealer),
                    failCallback: function (err) {
                        if (err) {
                            tips.setError(err);
                        }
                    },
                    customCheck: function () {
                        var vr = $.validator.createResult();
                        var dealerid = $($.dcorder.oDealer).val();
                        if (dealerid == "" || dealerid == "0") {
                            vr.errMsg = "请选择经销商";
                            vr.success = false;
                        } else {
                            vr.success = true;
                        }
                        return vr;
                    }
                }).IsPass();
            }
        },
        validate: function () {
            var success = true;
            for (var f in this.validateFn) {
                if (this.validateFn.hasOwnProperty(f)) {
                    success = this.validateFn[f]() && success;
                }
            }
            return success;
        },
        loaddealer: function (cid) {
            $.ajax({
                type: "GET",
                url: llb_global.config.api + "api/Base/GetDealers",
                timeout: 2000,
                data: { cityid: cid },
                dataType: 'jsonp',
                jsonp: "callback",
                jsonpCallback: "jsonpcallback.GetDealerCallback"
            });
        },
        loadprovince: function () {
            if (typeof (allcity) !== "undefined") {
                var html = "<option value=\"0\">请选择</option>", tpl = "<option value=\"{pid}\" data-name=\"{name}\">{pname}</option>";
                for (var i = 0; i < allcity.length; i++) {
                    html += tpl.replace("{pid}", allcity[i].ProvinceID).replace("{pname}", allcity[i].ProvinceName).replace("{name}", allcity[i].ProvinceName);
                }
                $("#J_province").html(html);
            }
        },
        loadcity: function (pid) {
            if (typeof (allcity) !== "undefined") {
                var html = "<option value=\"0\">请选择</option>", tpl = "<option value=\"{cid}\" data-name=\"{name}\">{cname}</option>";
                var pcitys = [];
                for (var i = 0; i < allcity.length; i++) {
                    if (allcity[i].ProvinceID == pid) {
                        pcitys = allcity[i].City;
                    }
                    else continue;
                }
                for (var j = 0; j < pcitys.length; j++) {
                    html += tpl.replace("{cid}", pcitys[j].CityID).replace("{cname}", pcitys[j].CityName).replace("{name}", pcitys[j].CityName);
                }
                $("#J_city").html(html);
            }
        },
        initLocation: function (data) {
            if (data.state == "success") {
                 var province = data.data.region || "北京市";
                var city = data.data.city || "北京市";
                $.dcorder.loadprovince();
                var poption = $("#J_province option[data-name='" + province + "']");
                poption.attr("selected", "selected");
                $.dcorder.loadcity(poption.val());
                var coption = $("#J_city option[data-name='" + city + "']");
                coption.attr("selected", "selected");
                $.dcorder.loaddealer(coption.val());
            }
        },
        sms: {
            sendsms: function () {
                tips.clearError();
                if (!$.dcorder.validateFn.checkPhone()) {
                    tips.show(tips.getError());
                    return false;
                }
                $.dcorder.utils.saveInput();
                wxApiAuth(function (openid) {
                    if (openid) {
                        llb_global.utils.setCookie("openid", openid);
                    }
                    $.ajax({
                        type: "GET",
                        url: llb_global.config.wxapi + "ajax_h5_get_sms_code&mobile=" + $($.dcorder.oPhone).val().trim(),
                        xhrFields: {
                            withCredentials: true
                        },
                        success: function () {
                            var sc = 30;
                            $($.dcorder.oSendSMSBtn).unbind("click").text(sc + "秒后重发");
                            var wt = setInterval(function () {
                                if (parseInt(sc, 10) > 1) {
                                    sc -= 1;
                                    $($.dcorder.oSendSMSBtn).unbind("click").text(sc + "秒后重发");
                                } else {
                                    clearInterval(wt);
                                    $($.dcorder.oSendSMSBtn).text("发送验证码").click(function () { $.dcorder.sms.sendsms(); });
                                }
                            }, 1000);
                        },
                        error: function (e) {
                            //alert("短信验证码发送失败");
                        }
                    });
                });
            }
        },

        __formData: {},
        submitOrderFlow: {
            completed: function () {
                $($.dcorder.btnSubmit).off("click").click($.dcorder.submitOrderFlow.submitOrder);
            },
            submitOrder: function () {
                var errMasker = tips;
                errMasker.clearError();
                if (!$.dcorder.validate()) {
                    errMasker.show();
                    return;
                }
                $($.dcorder.btnSubmit).off("click");
                $.dcorder.__formData = {
                    Phone: $($.dcorder.oPhone).val(),
                    Name: encodeURI($($.dcorder.oName).val()),
                    DealerID: $($.dcorder.oDealer).val(),
                    DealerCode: encodeURI($($.dcorder.oDealer).find("option:selected").text()),
                    SMSCode: $($.dcorder.oSMSCode).val(),
                    CityID: $($.dcorder.oCity).val(),
                    CityName: encodeURI($($.dcorder.oCity).find("option:selected").text().replace("请选择", "")),
                    ProvinceID: $($.dcorder.oProvince).val(),
                    ProvinceName: encodeURI($($.dcorder.oProvince).find("option:selected").text().replace("请选择", "")),
                    OpenID: llb_global.utils.readcookie("openid"),
                    CarTypeID: $("#J_carserial").find("option:selected").val(),
                    CarTypeName: encodeURI($("#J_carserial").find("option:selected").text())
                };

                $.ajax({
                    type: "GET",
                    url: llb_global.config.api + "api/Coupon/SubmitDriveOrder",
                    timeout: 2000,
                    data: $.dcorder.__formData,
                    dataType: 'jsonp',
                    jsonp: "callback",
                    jsonpCallback: "jsonpcallback.SubmitOrderCallback"
                });
            }

        }
    });
})(jQuery);
